package com.hfb.mashibing.alip8.jvm.c2_classloader;

import java.io.*;

/** custom ClassLoader 就是覆盖 Classloader 的 FindClass 方法
 *
 * @author hfb
 */
public class T006_CustomClassLoader extends ClassLoader {

//    String loadClassBasePath = "/Users/baiwang/git_hfb/tianyaxunai/alibaba-p8/target/classes";
    String loadClassBasePath = "/Users/baiwang/git_hfb/tianyaxunai/alibaba-p8/src/main/java";
    String filePath = loadClassBasePath;

    public static void main(String[] args) throws Exception {
        // 加载进来
        String loadClassPackagePath = "com.hfb.mashibing.alip8.jvm.classloader.HelloWorld";

        ClassLoader classLoader = new T006_CustomClassLoader();
        Class clazz = classLoader.loadClass(loadClassPackagePath);

        //反射调用方法
        HelloWorld h = (HelloWorld) clazz.newInstance();
        h.sayHello(null);


        System.out.println(classLoader.getClass().getClassLoader());
        System.out.println(classLoader.getParent());

    }

    @Override
    public Class<?> findClass(String className) throws ClassNotFoundException {
        File f = new File(filePath, className.replaceAll("\\.", File.separator).concat(".class"));
        try (FileInputStream fin = new FileInputStream(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

            int b = 0;
            while ((b = fin.read()) != 0) {
                baos.write(b);
            }
            byte[] bytes = baos.toByteArray();

            return defineClass(className, bytes, 0, bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return super.findClass(className);
    }
}
